#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <linux/fb.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <wchar.h>
#include <sys/ioctl.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#include "font_manager.h"

static FT_Face g_tface;
static int g_iDefaultFontSize = 12;

// 初始化FreeType库并创建字面量face
static int FT_FontInit(char *fontFile)
{   
    FT_Library library;

    int error;
    error = FT_Init_FreeType( &library );
    if (error)
    {
        printf("FT_Init_FreeType failed.\n");
        return -1;
    }
    error = FT_New_Face( library, fontFile, 0, &g_tface );
    if (error)
    {
        printf("FT_New_Face failed.\n");
        return -1;
    }
    FT_Set_Pixel_Sizes(g_tface, g_iDefaultFontSize, 0);
    return 0;
}


static int FT_SetFontSize(int iFontSize)
{
    FT_Set_Pixel_Sizes(g_tface, iFontSize, 0);
    return 0;
}


static int FT_GetFontBitMap(unsigned int dwCode, PFontBitMap ptFontBitMap)
{
    int error;
    FT_Vector pen;
    FT_GlyphSlot slot = g_tface->glyph;

    pen.x = ptFontBitMap->iCurOriginX * 64; /* 单位: 1/64像素 */
    pen.y = ptFontBitMap->iCurOriginY * 64; /* 单位: 1/64像素 */

	/* 转换：transformation */
	FT_Set_Transform(g_tface, 0, &pen);

	/* 加载位图: load glyph image into the slot (erase previous one) */
	error = FT_Load_Char(g_tface, dwCode, FT_LOAD_RENDER);
	if (error)
	{
		printf("FT_Load_Char error\n");
		return -1;
	}

	ptFontBitMap->pPixelDatas = slot->bitmap.buffer;

	ptFontBitMap->tRegion.iLeftUpX = slot->bitmap_left;
	ptFontBitMap->tRegion.iLeftUpY = ptFontBitMap->iCurOriginY*2 - slot->bitmap_top;
	ptFontBitMap->tRegion.iWidth   = slot->bitmap.width;
	ptFontBitMap->tRegion.iHeigh   = slot->bitmap.rows;
	ptFontBitMap->iNextOriginX = ptFontBitMap->iCurOriginX + slot->advance.x / 64;
	ptFontBitMap->iNextOriginY = ptFontBitMap->iCurOriginY;

	return 0;
}


static FontOpr g_tFreeTypeOpr = {
    .name = "FreeType",
    .FontInit = FT_FontInit,
    .SetFontSize = FT_SetFontSize,
    .GetFontBitMap = FT_GetFontBitMap,
};


void RegisterFTtoFontList(void)
{
	RegisterFont(&g_tFreeTypeOpr);
}